package com.group.flagtivities;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class CustomMapView extends MapView {

	private static final int LONGPRESS_THRESHOLD = 1000;
	private Timer longPressTimer;
	private OnLongPressListener longPressListener;
	
	public interface OnLongPressListener {
		public void onLongPress(MapView view, GeoPoint longPressLocation);
	}
	
	public CustomMapView(Context context, String apiKey) {
		super(context, apiKey);
	}

	public CustomMapView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CustomMapView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	public void setOnLongPressListener(OnLongPressListener listener) {
		longPressListener = listener;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		handleLongPress(event);
		return super.onTouchEvent(event);
	}
	
	private void handleLongPress(final MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN && event.getPointerCount() == 1) {
			longPressTimer = new Timer();
			longPressTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					GeoPoint longPressLocation = getProjection().fromPixels((int)event.getX(), (int)event.getY());
					longPressListener.onLongPress(CustomMapView.this, longPressLocation);
				}
			}, LONGPRESS_THRESHOLD);
		}
		else if (event.getAction() == MotionEvent.ACTION_MOVE) {
			longPressTimer.cancel();
		}
		else if (event.getAction() == MotionEvent.ACTION_UP) {
			longPressTimer.cancel();
		}
	}
	
}
